<template>
	<div class="app-container">
		<div class="table-wrapper">
			<h4>典型建筑物概率地震易损性分析数据</h4>
			<!-- 编辑 -->
			<el-form :inline="true" ref="formRef" :disabled="route.query.isView&&(route.query.calculateOrNot=='1')" :rules="rules" label-position="right" :model="params" label-width="200px">
				<div class="form-inline">
					<el-row justify="center">
						<el-col :span="11">
							<el-form-item label="编号：" class="form-item"><el-input v-model="params.number" placeholder=""
									:disabled="true" clearable /></el-form-item>
						</el-col>
						<el-col :span="11">
							<el-form-item label="用途：">
								<el-col :span="12">
									<el-form-item prop="purpose0">
										<el-select v-model="params.purpose0" placeholder="请选择" class="form-select"
											@change="useChange" clearable>
											<el-option v-for="item in useOptions" :key="item.value" :label="item.label"
												:value="item.value"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :span="1" class="text-center"><span class="text-gray-500">-</span></el-col>
								<el-col :span="11">
									<el-form-item prop="purpose1">
										<el-select v-model="params.purpose1" placeholder="请选择" class="form-select"
											clearable>
											<el-option v-for="item in use1Options" :key="item.value" :label="item.label"
												:value="item.value"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row justify="center">
						<el-col :span="11">
							<el-form-item label="区域：" class="form-item" prop="province">
								<el-form-item prop="province" style="width:120px;margin-right:10px;">
									<el-select v-model="params.province" placeholder="请选择省" @change="chooseProvince"
										clearable :disabled="!isAdd" value-key="id">
										<el-option v-for="item in provinceData" :key="item.id" :label="item.name"
											:value="item"></el-option>
									</el-select>
								</el-form-item>
								<el-form-item prop="city" style="width:120px;margin-right:10px;">
									<el-select v-model="params.city" placeholder="请选择市" @change="chooseCity" clearable
										:disabled="!isAdd" value-key="id">
										<el-option v-for="item in cityData" :key="item.id" :label="item.name"
											:value="item"></el-option>
									</el-select>
								</el-form-item>
								<el-form-item prop="county" style="width:120px;">
									<el-select v-model="params.county" placeholder="请选择县" @change="chooseCounty"
										:disabled="!isAdd" clearable value-key="id">
										<el-option v-for="item in areaData" :key="item.id" :label="item.name"
											:value="item"></el-option>
									</el-select>
								</el-form-item>
							</el-form-item>
						</el-col>
						<el-col :span="11">
							<el-form-item label="结构类型：" class="form-item" prop="structureType0">
								<el-col :span="12">
									<el-form-item prop="structureType0">
										<el-select v-model="params.structureType0" placeholder="请选择" class="form-select"
											@change="structureTypeChange" clearable :disabled="!isAdd">
											<el-option v-for="item in structureTypeOptions" :key="item.value"
												:label="item.label" :value="item.value"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :span="1" class="text-center"><span class="text-gray-500">-</span></el-col>
								<el-col :span="11">
									<el-form-item prop="structureType1">
										<el-select v-model="params.structureType1" placeholder="请选择" class="form-select"
											clearable :disabled="!isAdd">
											<el-option v-for="item in structureType1Options" :key="item.value"
												:label="item.label" :value="item.value"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row justify="center">
						<el-col :span="22">
							<el-form-item label="层数：" class="form-item" prop="cs">
								<!-- <el-input-number v-model="params.cs" placeholder="请输入" :min="0" :maxlength="10" clearable /> -->
								<el-select v-model="params.cs" placeholder="请选择" class="form-select" clearable :disabled="disabledcs">
									<el-option v-for="item in csOptions" :key="item.value" :label="item.label"
										:value="item.value">
									</el-option>
								</el-select>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row justify="center">
						<el-col :span="11">
							<el-form-item label="设防情况：" class="form-item" prop="fortification">
								<el-select v-model="params.fortification" placeholder="请选择" class="form-select" clearable
									:disabled="!isAdd">
									<el-option v-for="item in fortificationOptions" :key="item.value" :label="item.label"
										:value="item.value"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="11">
							<el-form-item label="年代：" class="form-item" prop="years">
								<el-select v-model="params.years" placeholder="请选择" class="form-select" clearable
									:disabled="!isAdd">
									<el-option v-for="item in yearsOptions" :key="item.value" :label="item.label"
										:value="item.value"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row v-if="!isAdd" justify="center">
						<el-col :span="11">
							<el-form-item label="维护人：" class="form-item" prop="userName"><el-input v-model="params.userName"
									placeholder="" clearable /></el-form-item>
						</el-col>
						<el-col :span="11">
							<el-form-item prop="createTime" label="维护时间:">
								<el-date-picker clearable v-model="params.createTime" type="datetime" placeholder="维护时间"
									value-format="YYYY-MM-DD HH:mm:ss" />
							</el-form-item>
						</el-col>
					</el-row>
					<el-row v-if="!isAdd" justify="center">
						<el-col :span="22">
							<el-form-item label="维护人所属单位：" class="form-item" prop="createUnit" style="width: 100%;">
								<el-input v-model="params.createUnit" placeholder="" clearable />
							</el-form-item>
						</el-col>
					</el-row>
					<el-row justify="center">
						<el-col :span="22">
							<el-form-item label="备注：" class="form-item" prop="commentInfo" style="width: 100%;">
								<el-input type="textarea" v-model="params.commentInfo" placeholder="" clearable />
							</el-form-item>
						</el-col>
					</el-row>
					<!-- 不是已计算状态的可以进行计算、保存 -->
					<el-row justify="end" v-if="params.calculateOrNot != 1">
						<el-form-item class="bottom-button">
							<el-popover placement="top-start" title="提示" :width="200" trigger="hover"
								content="计算结果不保存，若需要保存，请计算完成后点击页面“保存”按钮进行保存！">
								<template #reference>
									<el-button type="primary" @click="onRecalculate(formRef)" v-preventReClick>
										<el-icon>
											<EditPen />
										</el-icon>计算
									</el-button>
								</template>
							</el-popover>
							<el-button type="primary" @click="onSave(formRef)" v-preventReClick>
								<el-icon><Select /></el-icon>保存
							</el-button>
							<el-button @click="onRest(formRef)">
								<el-icon>
									<Refresh />
								</el-icon>重置
							</el-button>
						</el-form-item>
					</el-row>
				</div>
			</el-form>

			<!-- 表格1 -->
			<!-- <div class="page-panel">
				<el-table class="listTable" ref="multipleTableRef" border :data="tableData" style="width: 100%"
					:cell-style="{ border: '1px solid #e5ebf7' }"
					:header-cell-style="{ border: '1px solid #e5ebf7', borderLeft: 'none' }">
					<el-table-column prop="title" width="120" label="" />
					<el-table-column prop="sd" header-align="center" align="center" label="SD">
						<template #default="scope">
							<el-input v-model="scope.row.sd" placeholder="请输入" maxlength="10" />
						</template>
					</el-table-column>
					<el-table-column prop="st" header-align="center" align="center" label="MD">
						<template #default="scope">
							<el-input v-model="scope.row.md" placeholder="请输入" maxlength="10" />
						</template>
					</el-table-column>
					<el-table-column prop="years" header-align="center" align="center" label="ED">
						<template #default="scope">
							<el-input v-model="scope.row.ed" placeholder="请输入" maxlength="10" clearable />
						</template>
					</el-table-column>
					<el-table-column prop="fortification" header-align="center" align="center" label="Collapse">
						<template #default="scope">
							<el-input v-model="scope.row.collapse" placeholder="请输入" maxlength="10" clearable />
						</template>
					</el-table-column>
				</el-table>
			</div> -->

			<!-- 表格2 -->
			<div class="page-panel">
				<!-- 数据导入弹框 -->
				<import-data v-if="showParamsDialog" v-model="showParamsDialog" ref="paramsDialog" :uploadUrl="urlPsa"
					:isShow="true" downloadFileName="概率地震易损性分析数据模板.xlsx" @importSuccess="onImport"></import-data>
				<!-- 不显示折叠面板 -->
				<!-- <el-collapse v-if="false" v-model="activeNames" @change="handleChange">
					<el-collapse-item name="1">
						<template #title>
							<h1 style="font-size: 24px;">
								地震动参数：
								<el-button v-if="params.calculateOrNot != 1" type="primary"
									@click.stop.prevent="showParamsDialog = true">导入参数数据</el-button>
								<el-button type="primary" @click.stop.prevent="onExportParamsData">导出参数数据</el-button>
								<el-button v-if="activeNames == '1'" type="primary"
									@click.stop.prevent="onClickUse">应用</el-button>
							</h1>
						</template>
						<el-table class="listTable" ref="multipleTableRef" border :data="tableDataParameter"
							style="width: 100%" :cell-style="{ border: '1px solid #FaFaFa' }"
							:header-cell-style="{ border: '1px solid #FaFaFa', borderLeft: 'none', borderTop: 'none' }">
							<el-table-column type="index" width="55" label="序号" fixed="left" />
							<el-table-column label="操作" width="80" fixed="left" header-align="center" align="center">
								<template #default="scope">
									<el-button @click.prevent="handleCalcRemove(tableDataParameter, scope.$index)"
										type="text" size="small">删除</el-button>
								</template>
							</el-table-column>
							<el-table-column prop="dzdParams" header-align="center" align="center" label="地震动参数">
								<template #default="{ row }">
									<el-input type="number" v-model="row.dzdParams" placeholder="请输入" maxlength="10"
										clearable @change="onInputChange(row.dzdParams)" />
								</template>
							</el-table-column>
							<el-table-column prop="responseParams" header-align="center" align="center" label="结构响应参数">
								<template #default="{ row }">
									<el-input type="number" v-model="row.responseParams" placeholder="请输入" maxlength="10"
										clearable @change="(value) => row.responseParams = proxy.decimalPlaces(value, 4)" />
								</template>
							</el-table-column>
						</el-table>
						<el-button class="add" style="width: 100%" :plain="true"
							@click="handleCalcAdd(tableDataParameter, 'dzdParams')">
							<el-icon style="vertical-align: middle">
								<Plus />
							</el-icon>
						</el-button>
						<p class="be-careful">注：以上值均输入/导入，保留4位小数。</p>
					</el-collapse-item>
				</el-collapse> -->
				<h1 style="font-size: 24px; margin-bottom: 12px;">
					概率地震易损性需求分析数据：
					<el-button v-if="params.calculateOrNot != 1" type="primary"
						@click.stop.prevent="showParamsDialog = true">导入参数数据</el-button>
					<!-- params.calculateOrNot == 1 -->
					<el-button v-if="tableDataParameter.length" type="primary"
						@click.stop.prevent="onExportParamsData">导出参数数据</el-button>
					<el-button v-if="activeNames == '1'" type="primary" @click.stop.prevent="onClickUse">应用</el-button>
				</h1>
				<h1 style="font-size: 24px; margin-bottom: 12px;">
					结构响应视频：
					<FileUpload v-if="params.calculateOrNot != 1" v-model="params.fileList" :isShowTip="false" :limit="1"
						:fileType="fileType" :isFlex="true" @uploadFileCallback="uploadFileCallback"
						@delFile="delFileCallback"></FileUpload>
					<el-link v-else @click="handleDownloadFile(1)" :underline="false" target="_blank">
						<span class="el-icon-document">&nbsp;&nbsp;{{ params.srvName }} </span>
					</el-link>
				</h1>
				<h1 style="font-size: 24px;margin-bottom: 20px;">
					地震动时程：
					<el-button v-if="params.calculateOrNot != 1" type="primary"
						@click.stop.prevent="showGroundMotionDialog = true">导入文件</el-button>
					<template v-if="params.gmrcpId">
						<el-link v-if="params.calculateOrNot != 1" @click="handleDownloadFile(2)" :underline="false"
							target="_blank">
							<span class="el-icon-document">&nbsp;&nbsp;{{ groundMotionData.attachName }} </span>
						</el-link>
						<el-link v-else @click="handleDownloadFile(3)" :underline="false" target="_blank">
							<span class="el-icon-document">&nbsp;&nbsp;{{ params.gmrcpName }} </span>
						</el-link>
						<el-button type="primary" circle @click.stop.prevent="onDeleteGroundMotion()"
							style="margin-left: 20px;" :disabled="route.query.isView&&(route.query.calculateOrNot=='1')">
							<el-icon>
								<Delete />
							</el-icon>
						</el-button>
					</template>
				</h1>
				<!-- 导入地震动响应曲线参数 -->
				<import-data v-if="showGroundMotionDialog" v-model="showGroundMotionDialog" ref="paramsDialog"
					:uploadUrl="urlGM" downloadFileName="地震动时程.xlsx" @importSuccess="onImportGroundMotion"></import-data>
				<!-- 散点图 -->
				<div v-show="showParamsChart" ref="paramsChartRef" style="width: 680px;height:600px;margin: 0 auto;"></div>
				<el-form :inline="true" :disabled="route.query.isView&&(route.query.calculateOrNot=='1')" ref="formFormulaRef" label-position="right" :model="formFormula">
					<div>
						<el-form-item>
							<!-- 公式 -->
							<Formula fontSize="20px" tagOffset="-6px" :option="[
								{ content: '㏑' },
								{ content: '(' },
								{ content: 'm', sub: 'D|IM' },
								{ content: ')' },
								{ content: '=', margin: '0 8px' },
								{ content: 'β', sub: '0' },
								{ content: '+' },
								{ content: 'β', sub: '1' },
								{ content: '㏑' },
								{ content: 'IM', skew: '-15deg' },
							]"></Formula>
							<!-- 公式 -->
							<Formula fontSize="20px" tagOffset="-6px" style="margin-left: 32px;" :option="[
								{ content: 'β', sub: '0' },
								{ content: '=', margin: '0 8px' },
							]"></Formula>
							<el-form-item prop="param1">
								<el-input v-model="formFormula.param1" placeholder="β0" clearable />
							</el-form-item>
							<!-- 公式 -->
							<Formula fontSize="20px" tagOffset="-6px" :option="[
								{ content: 'β', sub: '1' },
								{ content: '=', margin: '0 8px' },
							]"></Formula>
							<el-form-item prop="param2">
								<el-input v-model="formFormula.param2" placeholder="β1" clearable />
							</el-form-item>
						</el-form-item>
					</div>
					<div>
						<el-form-item>
							<!-- 多行公式 -->
							<MultilineFormula display="inline-block" fontSize="20px" tagOffset="-6px" :option="[
								{ content: 'β', sub: 'D|IM' },
								{ content: '=', margin: '0 8px' },
								{
									radical: true,
									rows: [
										[
											// { content: '|', fontSize: '45px', width: '15px' },
											{ content: '∑', scale: 1.5, topContent: 'N', bottomContent: 'i=1' },
											{ content: '[' },
											{ content: '㏑' },
											{ content: '(' },
											{ content: 'D', sub: 'i' },
											{ content: ')' },
											{ content: '-', margin: '0 8px' },
											{ content: '㏑' },
											{ content: '(' },
											{ content: 'm', sub: 'D|IM' },
											{ content: ')' },
											{ content: ']', super: 2 },
											// { content: '|', fontSize: '45px', width: '15px' },
										],
										[{ content: 'N - 2' }],
									]
								}
							]"></MultilineFormula>
							<span style="margin: 0 8px;">=</span>
							<el-form-item prop="param3">
								<el-input v-model="formFormula.param3" placeholder="βdlm" clearable />
							</el-form-item>
						</el-form-item>
					</div>
					<div>
						<el-form-item>
							<!-- 多行公式 -->
							<MultilineFormula display="inline-block" fontSize="20px" tagOffset="-6px" :option="[
								{ content: 'R', super: '2' },
								{ content: '=', margin: '0 8px' },
								{
									rows: [
										[
											{ content: '∑', scale: 1.5, topContent: 'N', bottomContent: 'i=1' },
											{ content: '(' },
											{ content: 'λ', sub: 'i', topContent: '︿', tagLineHeight: '0' },
											{ content: '-' },
											{ content: 'λ' },
											{ content: ')', super: 2 },
										],
										[
											{ content: '∑', scale: 1.5, topContent: 'N', bottomContent: 'i=1' },
											{ content: '(' },
											{ content: 'D', sub: 'i' },
											{ content: '-' },
											{ content: 'λ' },
											{ content: ')', super: 2 },
										],
									]
								}
							]"></MultilineFormula>

							<span style="margin: 0 8px;">=</span>
							<el-form-item prop="param4">
								<el-input v-model="formFormula.param4" placeholder="R^2" clearable />
							</el-form-item>
						
						</el-form-item>
					</div>
					<div>
						<el-form-item>
								<!-- 公式 -->
								<Formula fontSize="20px" tagOffset="-6px" :option="[
								{ content: 'λ' },
								{ content: '=', margin: '0 8px' },
								{ content: 'D', sub: 'i' },
								{ content: '/' },
								{ content: 'N' },
							]"></Formula>

							<!-- 公式 -->
							<Formula fontSize="20px" tagOffset="-6px" style="margin-left: 30px;" :option="[
								{ content: 'λ', sub: 'i', topContent: '︿', tagLineHeight: '0' },
								{ content: '=', margin: '0 8px' },
								{ content: 'β', sub: '0' },
								{ content: '+' },
								{ content: 'β', sub: '1' },
								{ content: '㏑' },
								{ content: '(IM)' },
							]"></Formula>
						</el-form-item>
					</div>
				</el-form>
			</div>

			<!-- 表格3 -->
			<div class="page-panel">
				<h1 v-if="params.calculateOrNot != 1">
					请输入/导入<Formula tagOffset="-6px" :option="[{ content: 'm', sub: 'c' }]"></Formula>、<Formula
						tagOffset="-6px" :option="[{ content: 'β', sub: 'c' }]"></Formula>：
					<el-button type="primary" @click="showMcDialog = true" style="margin:20px 0;">导入</el-button>
					<span class="be-careful">（注：最多只能导入两行数据。）</span>
				</h1>
				<h1 v-else style="margin-bottom: 18px;">
					<Formula tagOffset="-6px" :option="[{ content: 'm', sub: 'c' }]"></Formula>、<Formula tagOffset="-6px"
						:option="[{ content: 'β', sub: 'c' }]"></Formula>：
				</h1>
				<!-- 数据导入弹框 -->
				<import-data v-if="showMcDialog" v-model="showMcDialog" ref="mcDialog" :uploadUrl="urlMc"
					downloadFileName="mc、βc导入模板.xlsx" @importSuccess="onImportMc"></import-data>
				<el-table class="listTable" ref="table3Ref" border :data="tableData3" style="width: 100%"
					:cell-style="{ border: '1px solid #FaFaFa' }"
					:header-cell-style="{ border: '1px solid #FaFaFa', borderLeft: 'none', borderTop: 'none' }">
					<el-table-column prop="title" header-align="center" align="center">
						<template #default="{ row }">
							<div v-if="row.type == 'S1'" style="margin: 10px;">
								<Formula tagOffset="-6px" :option="[{ content: 'm', sub: 'c' }]"></Formula>
							</div>
							<div v-else-if="row.type == 'mR,D'" style="margin: 10px;">
								<Formula tagOffset="-8px" :option="[{ content: 'm', sub: 'R,D' }]"></Formula>
							</div>
							<div v-else-if="row.type == 'B1'" style="margin: 10px;">
								<Formula tagOffset="-6px" :option="[{ content: 'β', sub: 'c' }]"></Formula>
							</div>
							<div v-else-if="row.type == 'βR,D'" style="margin: 10px;">
								<Formula tagOffset="-8px" :option="[{ content: 'β', sub: 'R,D' }]"></Formula>
							</div>
							<div v-else>{{ row.title }}</div>
						</template>
					</el-table-column>
					<el-table-column label="结构类型" header-align="center" align="center" width="350">
						<template #default="{ row }">
							<div v-if="row.type == 'S1'" style="margin: 10px;">
								<Formula tagOffset="-6px" :option="[{ content: 'S', sub: '1' }]"></Formula>
							</div>
							<div v-else-if="row.type == 'mR,D'" style="margin: 10px;">
								<MultilineFormula fontSize="20px" tagOffset="-6px" :option="[
									{ content: 'm', sub: 'R,D' },
									{ content: '=', margin: '0 8px' },
									{ content: '〔', scale: 2, margin: '0 8px 0 0' },
									{
										rows: [
											[{ content: 'm', sub: 'c' }],
											[
												{ content: 'exp' },
												{ content: '(' },
												{ content: 'β', sub: '0' },
												{ content: ')' },
											]
										]
									},
									{ content: '〕', scale: 2 },
									{ content: '1/β', scale: 0.8, top: '-15px', left: '-10px', sub: '1' },
								]"></MultilineFormula>
							</div>
							<div v-else-if="row.type == 'B1'" style="margin: 10px;">
								<Formula tagOffset="-6px" :option="[{ content: 'B', sub: '1' }]"></Formula>
							</div>
							<div v-else-if="row.type == 'βR,D'" style="margin: 10px;">
								<MultilineFormula fontSize="20px" tagOffset="-6px" :option="[
									{ content: 'β', sub: 'R,D' },
									{ content: '=', margin: '0 8px' },
									{ content: '〔', scale: 2, margin: '0 16px 0 0' },
									{
										rows: [
											[
												{
													radical: true,
													rows: [
														[
															{ content: 'β', sub: 'D|IM', super: '2' },
															{ content: '+' },
															{ content: 'β', sub: 'C', super: '2' },
														]
													]
												},
											],
											[{ content: 'β', sub: '1' }]
										]
									},
									{ content: '〕', scale: 2 },
									{ content: '1/β', scale: 0.8, top: '-20px', left: '-10px', sub: '1' },
								]"></MultilineFormula>
							</div>
							<div v-else>{{ row.type }}</div>
						</template>
					</el-table-column>
					<el-table-column prop="sd" label="轻微（SD）" header-align="center" align="center">
						<template #default="scope">
							<el-input v-if="scope.$index == 1 || scope.$index == 4" type="number" v-model="scope.row.sd" :disabled="route.query.isView&&(route.query.calculateOrNot=='1')"
								maxlength="10" readonly></el-input>
							<el-input v-else type="number" v-model="scope.row.sd" placeholder="请输入" maxlength="10" clearable
								@change="(value) => scope.row.sd = proxy.decimalPlaces(value, 4)" :disabled="route.query.isView&&(route.query.calculateOrNot=='1')"/>
						</template>
					</el-table-column>
					<el-table-column prop="md" label="中等（MD）" header-align="center" align="center">
						<template #default="scope">
							<el-input v-if="scope.$index == 1 || scope.$index == 4" type="number" v-model="scope.row.md"
								maxlength="10" readonly :disabled="route.query.isView&&(route.query.calculateOrNot=='1')"></el-input>
							<el-input v-else type="number" v-model="scope.row.md" placeholder="请输入" maxlength="10" clearable
								@change="(value) => scope.row.md = proxy.decimalPlaces(value, 4)" :disabled="route.query.isView&&(route.query.calculateOrNot=='1')"/>
						</template>
					</el-table-column>
					<el-table-column prop="ed" label="严重（ED）" header-align="center" align="center">
						<template #default="scope">
							<el-input v-if="scope.$index == 1 || scope.$index == 4" type="number" v-model="scope.row.ed"
								maxlength="10" readonly :disabled="route.query.isView&&(route.query.calculateOrNot=='1')"></el-input>
							<el-input v-else type="number" v-model="scope.row.ed" placeholder="请输入" maxlength="10" clearable
								@change="(value) => scope.row.ed = proxy.decimalPlaces(value, 4)" :disabled="route.query.isView&&(route.query.calculateOrNot=='1')"/>
						</template>
					</el-table-column>
					<el-table-column prop="collapse" label="倒塌（Collapse）" header-align="center" align="center">
						<template #default="scope">
							<el-input v-if="scope.$index == 1 || scope.$index == 4" type="number"
								v-model="scope.row.collapse" maxlength="10" readonly :disabled="route.query.isView&&(route.query.calculateOrNot=='1')"></el-input>
							<el-input v-else type="number" v-model="scope.row.collapse" placeholder="请输入" maxlength="10"
								clearable @change="(value) => scope.row.collapse = proxy.decimalPlaces(value, 4)" :disabled="route.query.isView&&(route.query.calculateOrNot=='1')"/>
						</template>
					</el-table-column>
				</el-table>
				<p class="be-careful">注：以上值均输入/导入，保留4位小数。</p>
			</div>

			<!-- 表格4 -->
			<div class="page-panel">
				<h1>
					请输入IM范围（0.01 ~ 2）：
					<el-form :inline="true" :disabled="route.query.isView&&(route.query.calculateOrNot=='1')" ref="formImRef" label-position="right" :model="formIm"
						style="display: inline-block;margin-bottom: 0;vertical-align: -webkit-baseline-middle;">
						<el-form-item label="起始IM值" prop="startValue">
							<el-input-number v-model="formIm.startValue" :min="0.01" :max="2" :step="formIm.intervalValue"
								clearable />
						</el-form-item>
						<el-form-item label="结束IM值" prop="endValue">
							<el-input-number v-model="formIm.endValue" :min="0.01" :max="2" :step="formIm.intervalValue"
								clearable />
						</el-form-item>
						<el-form-item label="自增跨度" prop="intervalValue">
							<el-input-number v-model="formIm.intervalValue" :min="0" :max="2" :step="0.01" clearable />
						</el-form-item>
					</el-form>
				</h1>
				<!-- 
				<el-table class="listTable" ref="table4Ref" border :data="tableData4" style="width: 100%"
					:cell-style="{ border: '1px solid #FaFaFa' }"
					:header-cell-style="{ border: '1px solid #FaFaFa', borderLeft: 'none', borderTop: 'none' }">
					<el-table-column label="操作" width="80" fixed="left" header-align="center" align="center">
						<template #default="scope">
							<el-button @click.prevent="handleCalcRemove(tableData4, scope.$index)" type="text"
								size="small">删除</el-button>
						</template>
					</el-table-column>
					<el-table-column prop="im" label="IM(g)" header-align="center" align="center"></el-table-column>
					<el-table-column prop="FIM" header-align="center" align="center">
						<template #header>
							<MultilineFormula fontSize="20px" tagOffset="-3px" :option="[
								{ content: 'F(IM)' },
								{ content: '=', margin: '0 8px' },
								{ content: 'Φ' },
								{ content: '[', scale: 2, margin: '0 8px 0 0' },
								{
									rows: [
										[
											{ content: '㏑(IM)' },
											{ content: '-' },
											{ content: '㏑(' },
											{ content: 'm', sub: 'R,D' },
											{ content: ')' },
										],
										[{ content: 'β', sub: 'R,D' }]
									]
								},
								{ content: ']', scale: 2, margin: '0 0 0 8px' },
							]"></MultilineFormula>
						</template>
						<el-table-column prop="fimSD" label="轻微（SD）" header-align="center" align="center">
							<template #default="scope">
								<el-input type="number" v-model="scope.row.fimSD" placeholder="请输入" maxlength="10" clearable
									@change="(value) => scope.row.fimSD = proxy.decimalPlaces(value, 4)" />
							</template>
						</el-table-column>
						<el-table-column prop="fimMD" label="中等（MD）" header-align="center" align="center">
							<template #default="scope">
								<el-input type="number" v-model="scope.row.fimMD" placeholder="请输入" maxlength="10" clearable
									@change="(value) => scope.row.fimMD = proxy.decimalPlaces(value, 4)" />
							</template>
						</el-table-column>
						<el-table-column prop="fimED" label="严重（ED）" header-align="center" align="center">
							<template #default="scope">
								<el-input type="number" v-model="scope.row.fimED" placeholder="请输入" maxlength="10" clearable
									@change="(value) => scope.row.fimED = proxy.decimalPlaces(value, 4)" />
							</template>
						</el-table-column>
						<el-table-column prop="fimCD" label="倒塌（Collapse）" header-align="center" align="center" width="140">
							<template #default="scope">
								<el-input type="number" v-model="scope.row.fimCD" placeholder="请输入" maxlength="10" clearable
									@change="(value) => scope.row.fimCD = proxy.decimalPlaces(value, 4)" />
							</template>
						</el-table-column>
					</el-table-column>
					<el-table-column prop="corrected" header-align="center" align="center">
						<template #header>
							<span class="color-red">修正值</span>
						</template>
						<template #default="scope">
							<el-input type="number" v-model="scope.row.corrected" placeholder="请输入" maxlength="10" clearable
								@change="(value) => scope.row.corrected = proxy.decimalPlaces(value, 4)" />
						</template>
					</el-table-column>
				</el-table>
				<el-button class="add" style="width: 100%" :plain="true" @click="handleCalcAdd(tableData4, 'IM')">
					<el-icon style="vertical-align: middle"><Plus/></el-icon>
				</el-button>
				<p class="be-careful">注：以上值均输入/导入，保留4位小数。</p>
				-->
				<div>
					根据公式
					<MultilineFormula fontSize="20px" tagOffset="-3px" display="inline-block" style="margin: 0 10px;"
						:option="[
							{ content: 'F(IM)' },
							{ content: '=', margin: '0 8px' },
							{ content: 'Φ' },
							{ content: '[', scale: 2, margin: '0 8px 0 0' },
							{
								rows: [
									[
										{ content: '㏑(IM)' },
										{ content: '-' },
										{ content: '㏑(' },
										{ content: 'm', sub: 'R,D' },
										{ content: ')' },
									],
									[{ content: 'β', sub: 'R,D' }]
								]
							},
							{ content: ']', scale: 2, margin: '0 0 0 8px' },
						]"></MultilineFormula>
					生成下列曲线：
				</div>
			</div>

			<!-- 图表 -->
			<div class="page-panel">
				<div>
					<el-button type="primary" @click="createLine">生成地震易损性曲线</el-button>
					<el-button type="primary" @click="downloadImpByChart">导出曲线</el-button>
				</div>
				<div ref="lineChartRef" style="width: 800px; height:600px;margin: 0 auto;"></div>
			</div>
		</div>
	</div>
</template>

<script setup>
import { reactive, ref, toRefs, nextTick } from 'vue';
// 引入store
import useUserStore from '@/store/modules/user';
import useDictStore from '@/store/modules/dict';
// 获取用户信息
import { getInfo } from '@/api/login';
// 引入接口
import {
	getCpvAnalysisByIdApi, //根据id查询详情
	psvExportExcelApi, //导出地震动参数
	uploadPsaUrl, //导入概率地震易损性分析数据Url
	uploadMcUrl, //导入mc、βc导入模板数据Url
	uploadGMUrl, //导入地震动响应曲线参数Url
	countCpvAnalysisApi, //计算β0、β1
	saveCpvInfoEntityApi, //保存概率地震易损性信息
} from '@/api/buildingVulnerAnalysis/buildingVulnerAnalysis.js';
import { getProvince, getChildArea } from '@/api/system/division';
// 公用方法
import { downloadFile } from "@/utils/ruoyi.js";
// 前端导出excel文件
import { export_json_to_excel } from '@/vendor/Export2Excel';
// 引入公式组件
import Formula from '@/components/Formula';
import MultilineFormula from '@/components/Formula/multiline';
// 引入导入弹框
import ImportData from "@/components/ImportData";
// 引入图表v5.4.2
import * as echarts from '@/utils/echarts-v5.4.2/echarts.esm.min.js';
// 引入图表数据处理
import ecStat from 'echarts-stat';

// 获取当前实例
const { proxy } = getCurrentInstance();
// 获取pinia
const userStore = useUserStore();
const dictStore = useDictStore();
// 全局路由对象
const router = useRouter();
// 当前路由对象
const route = useRoute();


// 是否是新增页，有路由参数是详情页，否则是新增页
let isAdd = computed(() => route.query.id ? false : true);
// 用户名
const userName = computed(() => userStore.name || '');
// 所属机构名称
const orgName = computed(() => userStore.orgName || '');
// 表单对象
const formRef = ref();
const formFormulaRef = ref();

// 导入数据接口路径
const urlPsa = ref(uploadPsaUrl);
const urlMc = ref(uploadMcUrl);
const urlGM = ref(uploadGMUrl);
// 文件下载接口根路径
const baseDownloadURL = import.meta.env.VITE_APP_BASE_API + "/attachment/downLoadFile?attachId=";

// 折叠面板
let activeNames = ref('0');
let showParamsChart = ref(false);

const data = reactive({
	// 表单参数
	params: {
		userName: '', //维护人
		createUnit: '', //维护人所属单位
		createTime: '', //维护时间
		cpviId: '', //id
		number: '', //编号
		purpose0: '', //用途
		purpose1: '',
		province: '', //省
		city: '', //市
		county: '', //县
		structureType0: '', //结构类型
		structureType1: '', //结构类型
		cs: undefined, //层数
		fortification: '', //设防情况
		years: '', //年代
		commentInfo: '', //备注
		calculateOrNot: false, //是否已计算

		param1: '', //β0的值
		param2: '', //β1的值
		param3: '', //βDIM的值
		param4: '', //R^2的值

		mcSd: '', //mc的SD的值
		mSd1: '', //mrd的SD的值
		mSd2: '', //mrd的SD的修正值

		pcSd: '', //βc的SD的值
		pSd1: '', //βrd的SD的值
		pSd2: '', //βrd的SD的修正值

		mcMd: '', //mc的MD的值
		mMd1: '', //mrd的MD的值
		mMd2: '', //mrd的MD的修正值

		pcMd: '', //βc的MD的值
		pMd1: '', //βrd的MD的值
		pMd2: '', //βrd的MD的修正值

		mcEd: '', //mc的ED的值
		mEd1: '', //mrd的ED的值
		mEd2: '', //mrd的ED的修正值

		pcEd: '', //βc的ED的值
		pEd1: '', //βrd的ED的值
		pEd2: '', //βrd的ED的修正值

		mcCd: '', //mc的倒塌(CD)的值
		mCd1: '', //mrd的倒塌(CD)的值
		mCd2: '', //mrd的倒塌(CD)的修正值

		pcCd: '', //βc的倒塌(CD)的值
		pCd1: '', //βrd的倒塌(CD)的值
		pCd2: '', //βrd的倒塌(CD)的修正值
		srvId: '',//视频id
		gmrcpId: '',//地震动响应id
	},
	// 表单验证规则
	rules: {
		// number: [{ required: true, message: '请选择', trigger: 'blur' }],
		fortification: [{ required: true, message: '请选择', trigger: 'change' }],
		years: [{ required: true, message: '请选择', trigger: 'change' }],
		province: [{ required: true, message: '请选择', trigger: 'change' }],
		structureType0: [{ required: true, message: '请选择', trigger: 'change' }]
	},
	// 设防情况
	fortificationOptions: dictStore.fortificationOptions || [],
	// 年份
	yearsOptions: dictStore.yearsOptions || [],
	// 层数
	csOptions: dictStore.csOptions || [],
	// 结构类型
	structureTypeOptions: dictStore.structureTypeOptions || [],
	structureType1Options: [],
	// 用途
	useOptions: dictStore.useOptions || [],
	use1Options: [],
	// 当前用途
	use0Label: '',
	use1Label: '',
	//表格
	tableData: [
		{ title: '中位值(mc)', sd: '0.002', md: '0.004', ed: '0.1', collapse: '0.2333' },
		{ title: '对数标准差(βc)', sd: '0.002', md: '0.0021', ed: '0.0221', collapse: '0.0321' },
	],

	// 参数表格
	tableDataParameter: [],
	// 公式计算结果表单
	formFormula: {
		param1: '', //β0的值
		param2: '', //β1的值
		param3: '', //βDIM的值
		param4: '', //R^2的值
	},
	tableData3: [
		{ title: 'mc', type: 'S1', sd: '', md: '', ed: '', collapse: '' },
		{ title: 'mR,D', type: 'mR,D', sd: '', md: '', ed: '', collapse: '' },
		{ title: '修正值', type: '——', sd: '', md: '', ed: '', collapse: '' },
		{ title: 'βc', type: 'B1', sd: '', md: '', ed: '', collapse: '' },
		{ title: 'βR,D', type: 'βR,D', sd: '', md: '', ed: '', collapse: '' },
		{ title: '修正值', type: '——', sd: '', md: '', ed: '', collapse: '' },
	],
	// IM范围表单
	formIm: {
		startValue: undefined,
		endValue: undefined,
		intervalValue: 0.05,
	},
	tableData4: [
		// {
		// 	im: '',
		// 	fimSD: '',
		// 	fimMD: '',
		// 	fimED: '',
		// 	fimCD: '',
		// 	corrected: '',
		// }
	],
	// IM表格原始列表
	listIM: [],

	// 显示参数导入弹框
	showParamsDialog: false,
	// 显示mc、βc导入弹框
	showMcDialog: false,
	// 显示导入地震动响应曲线参数
	showGroundMotionDialog: false,
	groundMotionData: {},
	fileType: ['avi', 'wmv', 'mpeg', 'mp4', 'm4v', 'mov', 'asf', 'flv', 'f4v', 'rmvb', 'rm', '3gp', 'vob'],
});
const {
	// 表单数据
	params,
	// 表单验证规则
	rules,
	// 设防情况选项
	fortificationOptions,
	// 年份选项
	yearsOptions,
	// 层数选项
	csOptions,
	// 结构类型选项
	structureTypeOptions,
	structureType1Options,
	// 用途选项
	useOptions,
	use1Options,
	// 当前用途
	use0Label,
	use1Label,
	// 表格数据
	tableData,
	tableDataParameter,
	// 公式计算结果表单
	formFormula,
	tableData3,
	// IM范围表单
	formIm,
	tableData4,
	// IM表格原始列表
	listIM,

	// 显示弹框
	showParamsDialog,
	showMcDialog,
	showGroundMotionDialog,
	groundMotionData,
	fileType,
} = toRefs(data);

/* 
	根据值获取用途
	params: {
		key: 值
	}
 */
function getUseByOptions(key) {
	const use = useOptions.value.find(item => item.value == key);
	return use ? (use.label || '') : '';
}
/* 
	根据值获取子用途
	params: {
		key1: 一级值
		key2: 二级值
	}
 */
function getChildUseByOptions(key1, key2) {
	const use = useOptions.value.find(item => item.value == key1);
	let childUse = {};
	if (use && use.children) {
		childUse = use.children.find(item => item.value == key2);
	}
	return childUse ? (childUse.label || '') : '';
}

// 行政区划选择
const provinceData = ref([]); //省
const cityData = ref([]); //市
const areaData = ref([]); //区、县
/** 获取省列表 */
function getProvinceData() {
	getProvince().then(response => {
		provinceData.value = response.data;
	});
}
// 选择省
function chooseProvince(value) {
	params.value.city = null;
	params.value.county = null;
	params.value.province = value.name;
	cityData.value = [];
	areaData.value = [];
	getChildArea(value.id).then(response => {
		cityData.value = response.data;
	});
}
// 选择市
function chooseCity(value) {
	params.value.city = value.name;
	params.value.county = null;
	areaData.value = [];
	getChildArea(value.id).then(response => {
		areaData.value = response.data;
	});
}
// 选择区县
function chooseCounty(value) {
	params.value.county = value.name;
}

// 结构类型选择
const disabledcs = ref(false);
const structureTypeChange = val => {
	const structureTypes = structureTypeOptions.value.find(item => item.value === val);
	if (structureTypes) {
		structureType1Options.value = structureTypes.children;
		params.value.structureType1 = '';
		// 清空用途
		params.value.purpose0 = '';
		params.value.purpose1 = '';
		use1Options.value = [];
		// 设防情况
		params.value.fortification = '';
		fortificationOptions.value = dictStore.fortificationOptions;
		// 年代
		yearsOptions.value = dictStore.yearsOptions;
		// 过滤楼层预选项
		if (val=='钢筋混凝土结构'||val=='钢结构') {
			csOptions.value = dictStore.csOptions;
			disabledcs.value = false;
			// 用途处理
			useOptions.value = dictStore.useOptions;
		} else if(val=='组合结构'){
			// 层数处理
			csOptions.value = dictStore.csOptions.filter((item, index) => index == 2);
			params.value.cs = ''
			disabledcs.value = false;
			// 用途处理
			useOptions.value = [
    	        {
    	            value: '第Ⅰ类',
    	            label: '第Ⅰ类',
    	            children: [
    	                {
    	                    value: '住宅',
    	                    label: '住宅'
    	                },
    	                {
    	                    value: '公寓',
    	                    label: '公寓'
    	                },
    	                {
    	                    value: '学生和职工集体宿舍',
    	                    label: '学生和职工集体宿舍'
    	                },
    	                {
    	                    value: '宾馆',
    	                    label: '宾馆'
    	                },
    	                {
    	                    value: '招待所',
    	                    label: '招待所'
    	                },
    	                {
    	                    value: '其他人员居住场所',
    	                    label: '其他人员居住场所'
    	                }
    	            ]
    	        },
    	        {
    	            value: '第Ⅱ类',
    	            label: '第Ⅱ类',
    	            children: [
    	                {
    	                    value: '办公室',
    	                    label: '办公室'
    	                },
    	            ]
    	        },
    	    ]
			// 设防情况
			fortificationOptions.value = dictStore.fortificationOptions.filter(item=>(item.value!='未设防'&&item.value!='自设防'));
		}else if(val=='砌体结构'){
			// 层数处理
			csOptions.value = dictStore.csOptions.filter((item, index) => index < 2);
			disabledcs.value = false;
			// 切换类型时，部分类型楼层没有就"9层以上"选项，则清空
			if (params.value.cs == '9层以上') {
				params.value.cs = ''
			}
			// 设防情况
			fortificationOptions.value = dictStore.fortificationOptions;
		}else{
			// 层数处理
			disabledcs.value = true;
			csOptions.value = [];
			params.value.cs = ''
			// 用途
			if(val=='土木结构'||val=='木结构'||val=='其他'){
				useOptions.value = [
    	        {
    	            value: '第Ⅰ类',
    	            label: '第Ⅰ类',
    	            children: [
    	                {
    	                    value: '住宅',
    	                    label: '住宅'
    	                },
    	                {
    	                    value: '其他人员居住场所',
    	                    label: '其他人员居住场所'
    	                }
    	            ]
    	        },
    	        {
    	            value: '第Ⅲ类',
    	            label: '第Ⅲ类',
    	            children: [
    	                {
    	                    value: '除I、II类以外',
    	                    label: '除I、II类以外'
    	                }
    	            ]
    	        }
    	    ]
			if(val=='土木结构'){
			// 设防情况
			fortificationOptions.value = dictStore.fortificationOptions.filter(item=>item.value=='未设防');
			yearsOptions.value = dictStore.yearsOptions.filter((item, index) => index < 4);
			// 切换类型时，年代--选项，则清空
			if (params.value.years == '2010-2016年'||params.value.years == '2016年以后') {
				params.value.years = ''
			}
			}else if(val=='其他'){
				fortificationOptions.value = dictStore.fortificationOptions.filter(item=>(item.value=='未设防'||item.value=='自设防'||item.value=='6度'));
			}
		}else{
				useOptions.value = [
    	        {
    	            value: '第Ⅱ类',
    	            label: '第Ⅱ类',
    	            children: [
    	                {
    	                    value: '生产车间',
    	                    label: '生产车间'
    	                },
    	            ]
    	        },
    	    ]
			}
		}
	}
};
// 选择用途
const useChange = val => {
	const use = useOptions.value.find(item => item.value === val);
	if (use) {
		use1Options.value = use.children;
	}
};

// 初始化获取数据
const getData = () => {
	const query = {
		id: route.query.id
	};
	getCpvAnalysisByIdApi(query)
		.then(res => {
			const { data } = res;
			if (res.code === 200 && data) {
				const { entity, list1, list2 } = data;
				// 基础数据
				if (entity) {
					// 根据返回数据设置变量的值
					setData(entity, list1, list2);
				}
				// 用途
				use0Label.value = getUseByOptions(params.purpose0);
				use1Label.value = getChildUseByOptions(params.purpose0, params.purpose1);
			} else {
				// 置空
				// tableData.value = [];
				tableDataParameter.value = [];
			}
		})
		.catch(err => {
			console.log(err);
		});
};
// 根据返回数据设置变量的值
function setData(entity, list1, list2) {
	params.value = {
		...entity,
		// 维护人
		userName: entity.userName || userName.value,
		// 维护人单位
		createUnit: entity.createUnit || orgName.value,
		// 维护时间
		createTime: entity.createTime || proxy.parseTime(new Date()),
	};
	// 中位值、对数标准差
	// tableData.value = [
	// 	{ title: '中位值(mc)', sd: entity.mcSd || '', md: entity.mcMd || '', ed: entity.mcEd || '', collapse: entity.mcCd || '' },
	// 	{ title: '对数标准差(βc)', sd: entity.pcSd || '', md: entity.pcMd || '', ed: entity.pcEd || '', collapse: entity.pcCd || '' },
	// ];
	// 地震动参数、结构响应参数
	tableDataParameter.value = list1 || [];
	if (list1 && list1.length) {
		// 散点图
		renderParamsChart(list1);
	}
	// β0、β1、βDIM、R^2
	formFormula.value = {
		param1: entity.param1 || '', //β0的值
		param2: entity.param2 || '', //β1的值
		param3: entity.param3 || '', //βDIM的值
		param4: entity.param4 || '', //R^2的值
	};
	// mc、βc
	tableData3.value = [
		{ title: 'mc', type: 'S1', sd: entity.mcSd || '', md: entity.mcMd || '', ed: entity.mcEd || '', collapse: entity.mcCd || '' },
		{ title: 'mR,D', type: 'mR,D', sd: entity.msd1 || '', md: entity.mmd1 || '', ed: entity.med1 || '', collapse: entity.mcd1 || '' },
		{ title: '修正值', type: '——', sd: entity.msd2 || '', md: entity.mmd2 || '', ed: entity.med2 || '', collapse: entity.mcd2 || '' },
		{ title: 'βc', type: 'B1', sd: entity.pcSd || '', md: entity.pcMd || '', ed: entity.pcEd || '', collapse: entity.pcCd || '' },
		{ title: 'βR,D', type: 'βR,D', sd: entity.psd1 || '', md: entity.pmd1 || '', ed: entity.ped1 || '', collapse: entity.pcd1 || '' },
		{ title: '修正值', type: '——', sd: entity.psd2 || '', md: entity.pmd2 || '', ed: entity.ped2 || '', collapse: entity.pcd2 || '' },
	];
	// 存储原始数据
	listIM.value = list2 || [];
	// IM范围值回显
	formIm.value = {
		startValue: entity.startValue || undefined,
		endValue: entity.endValue || undefined,
		intervalValue: entity.intervalValue || 0.05,
	};
	// IM表格的数据加载
	if (list2 && list2.length) {
		tableData4.value.length = 0;
		let arrKey = [];
		list2.map((item, index) => {
			// 根据行过滤
			if (!arrKey.includes(item.sum)) {
				arrKey.push(item.sum);
				// 设置当前行数据的值
				let curSum = item.sum;
				let curObj = {
					...item,
					corrected: '',
				};
				list2.map((item1, index1) => {
					if (curSum == item1.sum) {
						curObj['fim' + item1.breakState] = item1.fim;
					}
				})
				tableData4.value.push(curObj);
			}
		})
		if (tableData4.value.length) {
			// 生成地震易损性曲线
			createLine();
		}
	}
}
// 设置参数
function getApiParams() {
	// 计算参数
	const apiParams = {
		entity: {
			...params.value,
			// β0、β1、βDIM、R^2
			...formFormula.value,
			// IM范围值
			...formIm.value,
		},
		// 地震动参数和结构响应参数
		list1: tableDataParameter.value || [],
	};
	// 中位值、对数标准差
	// if(tableData.value.length) {
	// 	tableData.value.map((item, index) => {
	// 		switch(index) {
	// 			case 0:
	// 				apiParams.entity.mcSd = item.sd||'';
	// 				apiParams.entity.mcMd = item.md||'';
	// 				apiParams.entity.mcEd = item.ed||'';
	// 				apiParams.entity.mcCd = item.collapse||'';
	// 				break;
	// 			case 1:
	// 				apiParams.entity.pcSd = item.sd||'';
	// 				apiParams.entity.pcMd = item.md||'';
	// 				apiParams.entity.pcEd = item.ed||'';
	// 				apiParams.entity.pcCd = item.collapse||'';
	// 				break;
	// 		}
	// 	})
	// }
	// mc、βc
	if (tableData3.value.length) {
		tableData3.value.map((item, index) => {
			switch (index) {
				case 0:// mc
					apiParams.entity.mcSd = item.sd || '';
					apiParams.entity.mcMd = item.md || '';
					apiParams.entity.mcEd = item.ed || '';
					apiParams.entity.mcCd = item.collapse || '';
					break;
				case 1:// mR,D
					apiParams.entity.msd1 = item.sd || '';
					apiParams.entity.mmd1 = item.md || '';
					apiParams.entity.med1 = item.ed || '';
					apiParams.entity.mcd1 = item.collapse || '';
					break;
				case 2:// mR,D修正值
					apiParams.entity.msd2 = item.sd || '';
					apiParams.entity.mmd2 = item.md || '';
					apiParams.entity.med2 = item.ed || '';
					apiParams.entity.mcd2 = item.collapse || '';
					break;
				case 3:// βc
					apiParams.entity.pcSd = item.sd || '';
					apiParams.entity.pcMd = item.md || '';
					apiParams.entity.pcEd = item.ed || '';
					apiParams.entity.pcCd = item.collapse || '';
					break;
				case 4:// βR,D
					apiParams.entity.psd1 = item.sd || '';
					apiParams.entity.pmd1 = item.md || '';
					apiParams.entity.ped1 = item.ed || '';
					apiParams.entity.pcd1 = item.collapse || '';
					break;
				case 5:// βR,D修正值
					apiParams.entity.psd2 = item.sd || '';
					apiParams.entity.pmd2 = item.md || '';
					apiParams.entity.ped2 = item.ed || '';
					apiParams.entity.pcd2 = item.collapse || '';
					break;
			}
		})
	}
	// mc必填
	if (!apiParams.entity.mcSd) {
		proxy.$modal.msgWarning('请输入或导入mcSD值!');
		return false;
	}
	if (!apiParams.entity.mcMd) {
		proxy.$modal.msgWarning('请输入或导入mcMD值!');
		return false;
	}
	if (!apiParams.entity.mcEd) {
		proxy.$modal.msgWarning('请输入或导入mcED值!');
		return false;
	}
	if (!apiParams.entity.mcCd) {
		proxy.$modal.msgWarning('请输入或导入mcCD值!');
		return false;
	}
	// βc必填
	if (!apiParams.entity.pcSd) {
		proxy.$modal.msgWarning('请输入或导入βcSD值!');
		return false;
	}
	if (!apiParams.entity.pcMd) {
		proxy.$modal.msgWarning('请输入或导入βcMD值!');
		return false;
	}
	if (!apiParams.entity.pcEd) {
		proxy.$modal.msgWarning('请输入或导入βcED值!');
		return false;
	}
	if (!apiParams.entity.pcCd) {
		proxy.$modal.msgWarning('请输入或导入βcCD值!');
		return false;
	}
	// 去掉多余参数
	// 维护人
	delete apiParams.entity.userName;
	// 维护人单位
	delete apiParams.entity.createUnit;
	// 维护时间
	delete apiParams.entity.createTime;
	return apiParams;
}

// 获取用户
function getUserInfo(userId) {
	getInfo(userId).then(response => {
		params.value.userName = response.user.userName
		params.value.createUnit = response.user.orgName
	});
};

// 计算
const onRecalculate = async formEl => {
	if (!formEl) return;
	// 表单验证
	await formEl.validate((valid, fields) => {
		if (valid) {
			if (!(tableDataParameter.value && tableDataParameter.value.length)) {
				proxy.$modal.msgWarning('请输入地震动参数和结构响应参数!');
				return false;
			}
			// 设置参数
			const apiParams = getApiParams();
			if (apiParams) {
				proxy.$modal.loading('正在努力计算,请耐心等待！');
				countCpvAnalysisApi(apiParams).then(res => {
					proxy.$modal.closeLoading();
					const { data } = res;
					if (data) {
						const { entity, list1, list2 } = data;
						if (entity) {
							proxy.$modal.msgSuccess('计算完成！计算结果未保存，若需保存结果，请计算后点击保存按钮！');
							// 根据返回数据设置变量的值
							setData(entity, list1, list2);
						}
					}
				}).catch(err => {
					proxy.$modal.closeLoading();
				})
			}
		} else {
			proxy.$modal.msgWarning('表单验证失败，请检测填写数据！');
		}
	});
};
// 保存
const onSave = async (formEl) => {
	if (!formEl) return;
	// 表单验证
	await formEl.validate((valid, fields) => {
		if (valid) {
			if (!(tableDataParameter.value && tableDataParameter.value.length)) {
				proxy.$modal.msgWarning('请输入地震动参数和结构响应参数!');
				return false;
			}
			// 设置参数
			const apiParams = getApiParams();
			if (apiParams) {
				if (listIM.value.length) {
					tableData4.value.map((item, index) => {
						listIM.value.map((itemIM, indexIM) => {
							if (item.sum == itemIM.sum) {
								itemIM.fim = item['fim' + itemIM.breakState];
							}
						})
					})
				}
				apiParams.list2 = listIM.value || [];
				proxy.$modal.loading('正在保存,请耐心等待！');
				saveCpvInfoEntityApi(apiParams).then(res => {
					proxy.$modal.closeLoading();
					const { code, data } = res;
					if (code == 200 && data) {
						proxy.$modal.msgSuccess('保存成功!');
						// 跳转列表页
						close()
						// router.push({ path: '/buildingVulnerAnalysis/seismicVulnerAnalysis/seismicInquire' });
					} else {
						proxy.$modal.msgWarning(res.message || '保存失败!');
					}
				}).catch(err => {
					proxy.$modal.closeLoading();
					proxy.$modal.msgWarning(err.message || '保存失败!');
				})
			}
		} else {
			proxy.$modal.msgWarning('表单验证失败，请检测填写数据！');
		}
	})
};
/** 保存成功返回查询页 */
function close() {
  const obj = { path: "/buildingVulnerAnalysis/seismicVulnerAnalysis/seismicInquire" };
  proxy.$tab.closeOpenPage(obj);
};
// 重置
const onRest = (formEl) => {
	// 重置表单，方式一
	formEl.resetFields();
	// 重置表单，方式二
	// proxy.resetForm('formRef');
};

// 导入参数
const onImport = (response, uploadFile, uploadFiles) => {
	const { code, data } = response;
	if (code == 200 && data) {
		proxy.$modal.msgSuccess('导入数据成功!');
		// 地震动参数、结构响应参数
		tableDataParameter.value = data || [];
		// 散点图
		if (tableDataParameter.value.length) {
			renderParamsChart(tableDataParameter.value);
		}
	}
};
// 导入地震动参数
const onImportGroundMotion = (response) => {
	const { code, data } = response;
	if (code == 200 && data) {
		proxy.$modal.msgSuccess('导入数据成功!');
		params.value.gmrcpId = data[0].attachId
		groundMotionData.value = data[0];
	}
}
// 删除导入的地震动时程
const onDeleteGroundMotion = () => {
	proxy.$modal.confirm('请确认是否删除导入的地震动时程数据？').then(() => {
		params.value.gmrcpId = '';
		groundMotionData.value = {};
	});
}

// 下载文件
function handleDownloadFile(val) {
	if (val == 1) {
		location.href = baseDownloadURL + encodeURIComponent(params.value.srvId);
	}
	else if (val == 2) {
		location.href = baseDownloadURL + encodeURIComponent(groundMotionData.value.attachId);
	}
	else if (val == 3) {
		location.href = baseDownloadURL + encodeURIComponent(params.value.gmrcpId);
	}
}
// 视频上传成功回调
function uploadFileCallback(val) {
	if (val && val.length) {
		val.map(item => {
			params.value.srvId = val[0].attachId
		})
	} else {
		params.value.srvId = '';
	}
}
// 视频删除回调
function delFileCallback(index) {
	if (index && params.value.fileList) params.value.srvId = '';
}

// 导出参数数据
const onExportParamsData = () => {
	// 保存后通过接口导出
	// if (params.value.cpviId) {
	// 	psvExportExcelApi({
	// 		cpviId: params.value.cpviId || ''
	// 	}).then(res => {
	// 		if (res) {
	// 			downloadFile(res, `概率地震参数数据${params.value.number ? '(' + params.value.number + ')' : ''}.xlsx`);
	// 		} else {
	// 			proxy.$modal.msgError('导出概率地震参数数据失败！');
	// 		}
	// 	}).catch(err => {
	// 		proxy.$modal.msgError(err || '导出参数数据失败');
	// 	})
	// }

	// 前端导出
	if (tableDataParameter.value && tableDataParameter.value.length) {
		// 设置导出数据格式并导出
		const arrData = [];
		tableDataParameter.value.map((item, index) => {
			arrData.push([index + 1, item.dzdParams, item.responseParams]);
		});
		export_json_to_excel({
			// 表头
			header: ['序号', '地震动参数', '结构响应参数'],
			data: arrData,
			filename: '概率地震参数数据', //文件名
			autoWidth: true,
			bookType: 'xlsx',
		});
	} else {
		proxy.$modal.msgWarning('没有数据，无法导出！');
	}
}
// 导入mc、βc
const onImportMc = (response, uploadFile, uploadFiles) => {
	const { code, data } = response;
	if (code == 200 && data) {
		// 修改params
		Object.assign(params.value, data);
		// mc
		if (tableData3.value && tableData3.value[0]) {
			tableData3.value[0] = { title: 'mc', type: 'S1', sd: data.mcSd || '', md: data.mcMd || '', ed: data.mcEd || '', collapse: data.mcCd || '' };
		}
		// βc
		if (tableData3.value && tableData3.value[3]) {
			tableData3.value[3] = { title: 'βc', type: 'B1', sd: data.pcSd || '', md: data.pcMd || '', ed: data.pcEd || '', collapse: data.pcCd || '' };
		}
		// proxy.$modal.msgSuccess('导入数据成功!');
	}
};
// 增加表格行数据
const handleCalcAdd = (tableData, tabName) => {
	if (tabName == 'IM') {
		let im = formIm.value.startValue || 0.01;
		if (tableData.length) {
			// 获取表格最后一行im值
			const prevIm = tableData[tableData.length - 1].im;
			tableData.push({
				im: proxy.decimalPlaces(prevIm ? prevIm + 0.05 : im, 4)
			});
		} else {
			tableData.length = 0;
			tableData.push({ im: im });
		}
	}
	else if (tabName == 'dzdParams') {
		if (tableData && tableData.hasOwnProperty('length')) {
			tableData.push({
				dzdParams: '',
				responseParams: '',
			});
		}
	}
	else {
		if (tableData && tableData.hasOwnProperty('length')) {
			tableData.push({});
		}
	}
}
// 删除表格行数据
const handleCalcRemove = (tableData, index) => {
	if (tableData && tableData.length) {
		proxy.$modal.confirm('确定删除？').then(() => {
			tableData.splice(index, 1);
		})
	}
}
// 修改输入框值，保留4为小数
const onInputChange = (value) => {
	if (isNaN(value)) {
		proxy.$modal.msgWarning("请输入数字！");
	} else {
		value = proxy.decimalPlaces(value, 4);
	}
	return value;
}

// 折叠面板事件
function handleChange(val, old) {
	if (val && val.length) {
		activeNames.value = val[val.length - 1];
	}
}
// 应用表格数据
function onClickUse() {
	if (tableDataParameter.value.length) {
		// 散点图
		renderParamsChart(tableDataParameter.value);
	} else {
		proxy.$modal.msgWarning("表格数据为空，不能生成散点图！");
	}
}
// 散点图
let tChart = null;
async function renderParamsChart(data) {
	// 显示散点图
	showParamsChart.value = true;
	// DOM更新后执行
	await nextTick();
	if (!tChart) {
		tChart = echarts.init(proxy.$refs['paramsChartRef']);
	}
	if (tChart) {
		// 拟合数据
		let fitData = [];
		// 散点数据
		const arrData = [];
		// 排序
		// data.sort((a, b) => {
		// 	return a.dzdParamsLog < b.dzdParamsLog ? -1 : 1;
		// })
		// 遍历赋值
		data.map((item, index) => {
			// 原始值
			// arrData.push([item.dzdParams, item.responseParams]);
			// 对数值
			arrData.push([item.dzdParamsLog, item.responseParamsLog]);
			// 拟合直线
			// fitData.push([item.dzdParamsLog, item.straightLine]);
		});

		// 数据回归分析
		let myRegression = ecStat.regression('linear', arrData);
		// 这是线性回归到额参数，对于其它的回归类型，返回值有所不同
		myRegression.parameter = {
			gradient: 1.09,
			intercept: -2.65
		};
		// 拟合曲线的表达式
		myRegression.expression = 'y = 1.09x + -2.65';
		// 取开始、结束节点作拟合曲线数据
		if (myRegression.points && myRegression.points.length > 1) {
			fitData.push(myRegression.points[0]);
			fitData.push(myRegression.points[myRegression.points.length - 1]);
		}

		// See https://github.com/ecomfe/echarts-stat
		echarts.registerTransform(ecStat.transform.regression);
		const option = {
			dataset: [
				{
					source: arrData
				},
				{
					transform: {
						type: 'ecStat:regression',
						// echarts四种回归算法类型：'linear'（线性回归）、'exponential'（指数回归）、'logarithmic'（对数回归）、'polynomial'（多项式回归）
						config: {
							method: 'linear',  //线性回归
						}
					}
				}
			],
			toolbox: {
				//echart保存为图片
				show: true,
				feature: {
					mark: {
						show: true
					},
					restore: {
						show: true
					},
					saveAsImage: {
						show: true,
						pixelRatio: 1,
						title: '保存为图片',
						type: 'png',
						lang: ['点击保存']
					}
				}
			},
			tooltip: {
				trigger: 'axis',
			},
			xAxis: {
				name: '地震动参数',
				type: 'value',
				// 是否脱离0值比例
				scale: true,
				minInterval: 1,
				splitLine:{
					show:false
				}
			},
			yAxis: {
				name: '结构响应参数',
				type: 'value',
				nameTextStyle:{
					padding: [0, 0, 0, -870]
				},
				axisTick: {
   					show: false
				},
				axisLine: {
   					show: false
				},
				// // 最小、大间隔
				// minInterval: 0.0001,
				// maxInterval: 1,
				// interval: 0.05,
				// // 对数轴的底数
				// logBase: 10,
			},
			// 数据颜色
			// color: ['#107CE5', '#768dd1'],
			grid: {
				left: '10%',
				right: '12%',
				containLabel: true
			},
			series: [
				{
					name: '地震动参数',
					type: 'scatter',
					// symbolSize: 6,
					data: arrData,
					datasetIndex: 0,
					// // 大数据优化
					// larg: true,
					// // 开启绘制优化的阈值
					// largeThreshold: 2000,
				},
				{
					name: '拟合线',
					type: 'line',
					data: fitData || [],
					// 开启平滑处理
					// smooth: true,
					// 数据点
					symbolSize: 0.1,
					symbol: 'circle',
					datasetIndex: 1,
					label: { show: true, fontSize: 16 },
					labelLayout: { dx: -20 },
					encode: { label: 2, tooltip: 1 }
				}
			]
		};
		tChart.clear();
		tChart.setOption(option, true);
	}
}
//折线图
let myChart = null;
function renderChart() {
	if (!myChart) {
		myChart = echarts.init(proxy.$refs['lineChartRef']);
	}
	if (tableData4.value.length) {
		// x轴
		let xAxisData = [];
		// 预测值
		let cData = [];
		let edData = [];
		let mdData = [];
		let sdData = [];
		// 修正值
		let clData = [];
		let edlData = [];
		let mdlData = [];
		let sdlData = [];
		// 遍历赋值
		tableData4.value.map((item, index) => {
			xAxisData.push(item.im);
			// 预测值
			cData.push(item.fimCD);
			edData.push(item.fimED);
			mdData.push(item.fimMD);
			sdData.push(item.fimSD);
			// 修正值
			clData.push(item.fimCL);
			edlData.push(item.fimEDL);
			mdlData.push(item.fimMDL);
			sdlData.push(item.fimSDL);
		});
		const option = {
			toolbox: {
				//echart保存为图片
				show: true,
				feature: {
					mark: {
						show: true
					},
					restore: {
						show: true
					},
					saveAsImage: {
						show: true,
						pixelRatio: 1,
						title: '保存为图片',
						type: 'png',
						lang: ['点击保存']
					}
				}
			},
			legend: {
				data: ['轻微(SD)', '中等(MD)', '严重(ED)', '毁坏(Collapse)']
			},
			tooltip: {
				trigger: 'axis'
			},
			xAxis: {
				name: 'PGA/g',
				type: 'category',
				data: xAxisData
			},
			yAxis: {
				name: 'F(IM)',
				type: 'value',
				// axisLabel: {
				// 	formatter: '{value}'
				// }
			},
			// 数据颜色 '#739cef', '#ff0000'
			color: ['#de182b', '#2ad12e', '#030303', '#0401ed'],
			series: [
				// 预测值
				{
					name: '轻微(SD)',
					data: sdData,
					smooth: true,
					type: 'line'
				},
				{
					name: '中等(MD)',
					data: mdData,
					smooth: true,
					type: 'line'
				},
				{
					name: '严重(ED)',
					data: edData,
					smooth: true,
					type: 'line'
				},
				{
					name: '毁坏(Collapse)',
					data: cData,
					smooth: true,
					type: 'line'
				},

				// 预测值
				{
					name: '轻微修正值(SD)',
					data: sdlData,
					smooth: true,
					// 标记类型 'circle', 'rect', 'roundRect', 'triangle', 'diamond', 'pin', 'arrow', 'none'
					// symbol: 'none',
					symbolSize: 3,
					type: 'line',
					lineStyle: {
						color: '#de182b',
						width: 1,
						type: 'dashed'
					},
				},
				{
					name: '中等修正值(MD)',
					data: mdlData,
					smooth: true,
					// symbol: 'none',
					symbolSize: 3,
					type: 'line',
					lineStyle: {
						color: '#2ad12e',
						width: 1,
						type: 'dashed'
					},
				},
				{
					name: '严重修正值(ED)',
					data: edlData,
					smooth: true,
					// symbol: 'none',
					symbolSize: 3,
					type: 'line',
					lineStyle: {
						color: '#030303',
						width: 1,
						type: 'dashed'
					},
				},
				{
					name: '毁坏修正值(Collapse)',
					data: clData,
					smooth: true,
					// symbol: 'none',
					symbolSize: 3,
					type: 'line',
					lineStyle: {
						color: '#0401ed',
						width: 1,
						type: 'dashed'
					},
				}
			]
		};
		myChart.clear();
		myChart.setOption(option, true);
	} else {
		proxy.$modal.msgWarning("请先进行计算再生成曲线！");
	}
};
// 生成地震易损性曲线
function createLine() {
	//折线图
	renderChart();
}
// 导出曲线
function downloadImpByChart() {
	if (!myChart) {
		myChart = echarts.getInstanceByDom(proxy.$refs['lineChartRef']);
	}
	if (myChart) {
		var url = myChart.getConnectedDataURL({
			pixelRatio: 5, //导出的图片分辨率比率,默认是1
			backgroundColor: '#fff', //图表背景色
			excludeComponents: ['toolbox'], //保存图表时忽略的工具组件,默认忽略工具栏
			type: 'png' //图片类型支持png和jpeg
		});
		var $a = document.createElement('a');
		var type = 'png';
		var strTitle = myChart.getOption().title ? myChart.getOption().title[0].text : '地震易损性曲线';
		$a.download = strTitle + '.' + type;
		$a.target = '_blank';
		$a.href = url;
		// Chrome and Firefox
		if (typeof MouseEvent === 'function') {
			var evt = new MouseEvent('click', {
				view: window,
				bubbles: true,
				cancelable: false
			});
			$a.dispatchEvent(evt);
		}
		// IE
		else {
			var html = ''
			'<body style="margin:0;">'
			'![](' + url + ')'
			'</body>';
			var tab = window.open();
			tab.document.write(html);
		}
	} else {
		proxy.$modal.msgWarning("请先生成曲线再导出！");
	}
};

// 挂载
onMounted(() => {
	// 新增页
	if (isAdd.value) {
		// 获取登录用户信息
		params.value.userName = userName.value;
		params.value.createUnit = orgName.value;
		// 获取行政区划数据
		getProvinceData();
	} else {
		// 初始化获取数据
		getData();
	}
});
// 卸载前
onBeforeUnmount(() => {
	if (myChart) {
		myChart.dispose();
		myChart = null;
	}
});
</script>

<style lang="scss" scoped>
h1 {
	margin: 0;
}

.table-wrapper {
	position: relative;

	h4 {
		font-size: 16px;
		font-weight: bold;
		color: #107ce5;
		text-align: center;
	}
}

.el-descriptions,
.el-form {
	margin-bottom: 20px;
}

.form-inline {
	.el-form-item {
		margin-right: 0;
	}
}

.page-panel {
	margin-top: 40px;
}

.el-table {
	.el-form-item {
		margin: 0;
	}

	/* .el-input {
 		max-width: 200px;
 	} */
}

/* 字体红色 */
.color-red {
	color: red !important;
}

/* 注 */
.be-careful {
	text-align: center;
	color: red;
}
</style>
